/**
 * ETF网格交易3.0系统 - 综合策略压力测试
 * 整合2.1利润留存 + 2.2逐格加码 + 2.3大中小网策略
 * 遵循DRY、KISS、SOLID、YAGNI原则
 */

class GridTradingSystem3 {
    constructor() {
        this.gridData = [];
        this.priceHistory = [];
        this.profitHistory = [];
    }


    /**
     * 生成综合策略网格数据
     */
    generateComprehensiveGrid(params) {
        const {
            initialPrice, gridMode, baseAmount, maxDecline,
            enableProfitRetention,
            enableProgressiveBetting, progressiveMode, increaseRate, increaseAmount, startFromGrid,
            smallGridLayers, mediumGridLayers, largeGridLayers,
            smallGridSize, mediumGridSize, largeGridSize,
            smallGridStep, mediumGridStep, largeGridStep,
            smallGridProgressive, mediumGridProgressive, largeGridProgressive
        } = params;

        const allGrids = [];

        // 1. 小网（基础网格，支持利润留存和逐格加码）
        const smallGridData = this.generateGridWithProgressive({
            initialPrice, gridMode, gridSize: smallGridSize, gridStep: smallGridStep,
            baseAmount, gridCount: smallGridLayers, gridType: '小网',
            enableProfitRetention, enableProgressiveBetting: smallGridProgressive,
            progressiveMode, increaseRate, increaseAmount, startFromGrid
        });
        allGrids.push(...smallGridData);

        // 2. 中网
        const mediumGridData = this.generateGridWithProgressive({
            initialPrice, gridMode, gridSize: mediumGridSize, gridStep: mediumGridStep,
            baseAmount, gridCount: mediumGridLayers, gridType: '中网',
            enableProfitRetention, enableProgressiveBetting: mediumGridProgressive,
            progressiveMode, increaseRate, increaseAmount, startFromGrid
        });
        allGrids.push(...mediumGridData);

        // 3. 大网
        const largeGridData = this.generateGridWithProgressive({
            initialPrice, gridMode, gridSize: largeGridSize, gridStep: largeGridStep,
            baseAmount, gridCount: largeGridLayers, gridType: '大网',
            enableProfitRetention, enableProgressiveBetting: largeGridProgressive,
            progressiveMode, increaseRate, increaseAmount, startFromGrid
        });
        allGrids.push(...largeGridData);

        return allGrids;
    }

    /**
     * 生成网格数据（支持逐格加码和利润留存）
     */
    generateGridWithProgressive(params) {
        const {
            initialPrice, gridMode, gridSize, gridStep, baseAmount, gridCount, gridType,
            enableProfitRetention, enableProgressiveBetting,
            progressiveMode, increaseRate, increaseAmount, startFromGrid
        } = params;

        const gridData = [];
        let cumulativeRetainedShares = 0; // 累计剩余股数
        let totalAmount = 0; // 总投入金额

        // 小网从第一层开始，中网大网从第二层开始
        const startLayer = gridType === '小网' ? 0 : 1;
        const endLayer = gridType === '小网' ? gridCount : gridCount;

        for (let i = startLayer; i < endLayer; i++) {
            let buyPrice, sellPrice;
            
            if (gridMode === 'percentage') {
                buyPrice = initialPrice * Math.pow(1 - gridSize / 100, i);
                sellPrice = i === 0 ? initialPrice * (1 + gridSize / 100) : 
                           initialPrice * Math.pow(1 - gridSize / 100, i - 1);
            } else {
                buyPrice = initialPrice - (gridStep * i);
                sellPrice = i === 0 ? initialPrice + gridStep : 
                           initialPrice - (gridStep * (i - 1));
            }

            // 计算投入金额（逐格加码逻辑）
            let amount = baseAmount;
            if (enableProgressiveBetting && i >= startFromGrid - 1) {
                const increaseTimes = i - (startFromGrid - 1);
                if (progressiveMode === 'percentage') {
                    amount = baseAmount * Math.pow(1 + increaseRate / 100, increaseTimes);
                } else {
                    amount = baseAmount + (increaseAmount * increaseTimes);
                }
            }

            // 计算股数（100的整数倍，向上取整）
            const buyShares = Math.ceil(amount / buyPrice / 100) * 100;
            const sellShares = Math.ceil(amount / sellPrice / 100) * 100;
            
            // 调整金额以匹配股数（买入金额和卖出金额由最终向上取整后的股数乘以价位计算得出）
            const actualBuyAmount = buyShares * buyPrice;
            const actualSellAmount = sellShares * sellPrice;
            totalAmount += actualBuyAmount;
            
            // 利润留存逻辑：将全部利润转换为股数留存
            let actualSellShares = sellShares;
            let retainedShares = 0;
            if (enableProfitRetention) {
                const profit = actualSellAmount - actualBuyAmount;
                if (profit > 0) {
                    retainedShares = Math.ceil(profit / sellPrice / 100) * 100;
                    actualSellShares = sellShares - retainedShares;
                    cumulativeRetainedShares += retainedShares;
                }
            }

            // 计算剩余股数：买入股数 - 卖出股数
            const remainingShares = buyShares - actualSellShares;

            // 计算收益
            const actualReturn = (sellPrice - buyPrice) * actualSellShares;
            const returnRate = (sellPrice - buyPrice) / buyPrice * 100;

            gridData.push({
                gridType: gridType,
                level: i + 1,
                buyPrice: buyPrice.toFixed(4),
                sellPrice: sellPrice.toFixed(4),
                buyAmount: actualBuyAmount.toFixed(2),
                sellAmount: (actualSellShares * sellPrice).toFixed(2),
                buyShares: buyShares,
                sellShares: actualSellShares,
                remainingShares: remainingShares,
                expectedReturn: actualReturn.toFixed(2),
                returnRate: returnRate.toFixed(2),
                totalAmount: totalAmount.toFixed(2)
            });
        }

        return gridData;
    }

    /**
     * 生成大中小网数据
     */
    generateMultiGrid(params) {
        const {
            initialPrice, gridMode, totalAmount,
            smallGridRatio, mediumGridRatio, largeGridRatio,
            smallGridLayers, mediumGridLayers, largeGridLayers,
            smallGridSize, mediumGridSize, largeGridSize,
            smallGridStep, mediumGridStep, largeGridStep
        } = params;

        const allGrids = [];

        // 小网
        const smallGridAmount = totalAmount * (smallGridRatio / 100);
        const smallGrids = this.generateSingleGrid(initialPrice, gridMode, smallGridSize, smallGridStep, smallGridAmount, smallGridLayers, '小网');
        allGrids.push(...smallGrids);

        // 中网
        const mediumGridAmount = totalAmount * (mediumGridRatio / 100);
        const mediumGrids = this.generateSingleGrid(initialPrice, gridMode, mediumGridSize, mediumGridStep, mediumGridAmount, mediumGridLayers, '中网');
        allGrids.push(...mediumGrids);

        // 大网
        const largeGridAmount = totalAmount * (largeGridRatio / 100);
        const largeGrids = this.generateSingleGrid(initialPrice, gridMode, largeGridSize, largeGridStep, largeGridAmount, largeGridLayers, '大网');
        allGrids.push(...largeGrids);

        return allGrids;
    }

    /**
     * 生成单个网格数据（中网、大网）
     */
    generateSingleGrid(initialPrice, gridMode, gridSize, gridStep, totalAmount, gridCount, gridType, enableProfitRetention = true) {
        const gridData = [];
        const amountPerGrid = totalAmount / gridCount;
        let cumulativeRetainedShares = 0; // 累计剩余股数

        // 中网和大网从第二层开始（去掉第一层）
        for (let i = 1; i < gridCount; i++) {
            let buyPrice, sellPrice;
            
            if (gridMode === 'percentage') {
                buyPrice = initialPrice * Math.pow(1 - gridSize / 100, i);
                sellPrice = initialPrice * Math.pow(1 - gridSize / 100, i - 1);
            } else {
                buyPrice = initialPrice - (gridStep * i);
                sellPrice = initialPrice - (gridStep * (i - 1));
            }

            // 计算股数（100的整数倍，向上取整）
            const buyShares = Math.ceil(amountPerGrid / buyPrice / 100) * 100;
            const sellShares = Math.ceil(amountPerGrid / sellPrice / 100) * 100;
            
            // 调整金额以匹配股数
            const actualBuyAmount = buyShares * buyPrice;
            const actualSellAmount = sellShares * sellPrice;
            
            // 利润留存逻辑：将全部利润转换为股数留存
            let actualSellShares = sellShares;
            let retainedShares = 0;
            if (enableProfitRetention) {
                const profit = actualSellAmount - actualBuyAmount;
                if (profit > 0) {
                    retainedShares = Math.ceil(profit / sellPrice / 100) * 100;
                    actualSellShares = sellShares - retainedShares;
                    cumulativeRetainedShares += retainedShares;
                }
            }

            const expectedReturn = (sellPrice - buyPrice) * actualSellShares;
            const returnRate = (sellPrice - buyPrice) / buyPrice * 100;

            gridData.push({
                gridType: gridType,
                level: i,
                buyPrice: buyPrice.toFixed(4),
                sellPrice: sellPrice.toFixed(4),
                amount: actualBuyAmount.toFixed(2),
                buyShares: buyShares,
                sellShares: actualSellShares,
                retainedShares: cumulativeRetainedShares,
                expectedReturn: expectedReturn.toFixed(2),
                returnRate: returnRate.toFixed(2)
            });
        }

        return gridData;
    }

    /**
     * 模拟综合策略交易
     */
    simulateComprehensiveTrading(params, gridData) {
        const { initialPrice, maxDecline } = params;
        const priceHistory = [initialPrice];
        const profitHistory = [0];

        let currentPrice = initialPrice;
        let totalProfit = 0;
        let completedTrades = 0;
        let retainedProfits = 0;

        // 模拟价格下跌到最大跌幅
        const minPrice = initialPrice * (1 - maxDecline / 100);
        const steps = 100;
        
        for (let i = 1; i <= steps; i++) {
            // 模拟价格波动
            const declineProgress = i / steps;
            const basePrice = initialPrice * (1 - maxDecline / 100 * declineProgress);
            const randomFactor = 0.95 + Math.random() * 0.1;
            currentPrice = basePrice * randomFactor;

            priceHistory.push(currentPrice);

            // 检查所有网格的交易触发
            const newTrades = this.checkComprehensiveTriggers(currentPrice, gridData, completedTrades, params);
            totalProfit += newTrades.profit;
            retainedProfits += newTrades.retainedProfit || 0;
            completedTrades += newTrades.count;

            profitHistory.push(totalProfit);
        }

        return { 
            priceHistory, 
            profitHistory, 
            completedTrades, 
            totalProfit, 
            retainedProfits 
        };
    }

    /**
     * 检查综合策略的交易触发
     */
    checkComprehensiveTriggers(currentPrice, gridData, completedTrades, params) {
        let profit = 0;
        let retainedProfit = 0;
        let count = 0;

        for (let i = completedTrades; i < gridData.length; i++) {
            const grid = gridData[i];
            const buyPrice = parseFloat(grid.buyPrice);
            const sellPrice = parseFloat(grid.sellPrice);

            if (currentPrice <= buyPrice) {
                const baseReturn = parseFloat(grid.expectedReturn);
                const retained = parseFloat(grid.retainedProfit) || 0;
                
                profit += baseReturn;
                retainedProfit += retained;
                count++;
            }
        }

        return { profit, retainedProfit, count };
    }

    /**
     * 计算综合统计指标
     */
    calculateComprehensiveStatistics(gridData, simulationResult, params) {
        const { totalProfit, completedTrades, retainedProfits } = simulationResult;
        const totalAmount = gridData.reduce((sum, item) => sum + parseFloat(item.amount), 0);
        const totalReturnRate = (totalProfit / totalAmount) * 100;
        const avgReturnPerTrade = completedTrades > 0 ? totalProfit / completedTrades : 0;
        const maxDrawdown = this.calculateMaxDrawdown(simulationResult.profitHistory);

        // 按网格类型统计
        const gridTypeStats = this.calculateGridTypeStats(gridData, simulationResult);

        return {
            totalProfit: totalProfit.toFixed(2),
            totalReturnRate: totalReturnRate.toFixed(2),
            completedTrades,
            avgReturnPerTrade: avgReturnPerTrade.toFixed(2),
            maxDrawdown: maxDrawdown.toFixed(2),
            totalAmount: totalAmount.toFixed(2),
            retainedProfits: retainedProfits.toFixed(2),
            gridTypeStats
        };
    }

    /**
     * 按网格类型统计
     */
    calculateGridTypeStats(gridData, simulationResult) {
        const stats = {};
        const gridTypes = [...new Set(gridData.map(item => item.gridType))];
        
        gridTypes.forEach(type => {
            const typeGrids = gridData.filter(item => item.gridType === type);
            const typeAmount = typeGrids.reduce((sum, item) => sum + parseFloat(item.amount), 0);
            const typeReturn = typeGrids.reduce((sum, item) => sum + parseFloat(item.expectedReturn), 0);
            
            stats[type] = {
                amount: typeAmount.toFixed(2),
                expectedReturn: typeReturn.toFixed(2),
                returnRate: ((typeReturn / typeAmount) * 100).toFixed(2)
            };
        });

        return stats;
    }

    /**
     * 计算最大回撤
     */
    calculateMaxDrawdown(profitHistory) {
        let maxDrawdown = 0;
        let peak = 0;

        for (const profit of profitHistory) {
            if (profit > peak) {
                peak = profit;
            }
            const drawdown = peak - profit;
            if (drawdown > maxDrawdown) {
                maxDrawdown = drawdown;
            }
        }

        return maxDrawdown;
    }

    /**
     * 更新统计卡片
     */
    updateStatsGrid(stats) {
        const statsGrid = document.getElementById('statsGrid');
        const statsHTML = `
            <div class="stat-card">
                <h3>总收益</h3>
                <div class="value ${stats.totalProfit >= 0 ? 'profit' : 'loss'}">
                    ¥${stats.totalProfit}
                </div>
            </div>
            <div class="stat-card">
                <h3>总收益率</h3>
                <div class="value ${stats.totalReturnRate >= 0 ? 'profit' : 'loss'}">
                    ${stats.totalReturnRate}%
                </div>
            </div>
            <div class="stat-card">
                <h3>完成交易数</h3>
                <div class="value">${stats.completedTrades}</div>
            </div>
            <div class="stat-card">
                <h3>平均每笔收益</h3>
                <div class="value ${stats.avgReturnPerTrade >= 0 ? 'profit' : 'loss'}">
                    ¥${stats.avgReturnPerTrade}
                </div>
            </div>
            <div class="stat-card">
                <h3>最大回撤</h3>
                <div class="value loss">¥${stats.maxDrawdown}</div>
            </div>
            <div class="stat-card">
                <h3>总投入</h3>
                <div class="value">¥${stats.totalAmount}</div>
            </div>
            <div class="stat-card">
                <h3>保留利润</h3>
                <div class="value profit">¥${stats.retainedProfits}</div>
            </div>
        `;

        // 添加网格类型统计
        Object.entries(stats.gridTypeStats).forEach(([type, typeStats]) => {
            statsHTML += `
                <div class="stat-card">
                    <h3>${type}收益</h3>
                    <div class="value ${parseFloat(typeStats.expectedReturn) >= 0 ? 'profit' : 'loss'}">
                        ¥${typeStats.expectedReturn}
                    </div>
                </div>
            `;
        });

        statsGrid.innerHTML = statsHTML;
    }

    /**
     * 更新网格表格
     */
    updateGridTable(gridData) {
        const tbody = document.getElementById('gridTableBody');
        tbody.innerHTML = gridData.map(grid => `
            <tr>
                <td>${grid.gridType}</td>
                <td>${grid.level}</td>
                <td>${grid.buyPrice}</td>
                <td>¥${grid.buyAmount}</td>
                <td>${grid.buyShares}</td>
                <td>${grid.sellPrice}</td>
                <td>¥${grid.sellAmount}</td>
                <td>${grid.sellShares}</td>
                <td class="${grid.remainingShares > 0 ? 'profit' : ''}">${grid.remainingShares}</td>
                <td class="${parseFloat(grid.expectedReturn) >= 0 ? 'profit' : 'loss'}">
                    ¥${grid.expectedReturn}
                </td>
                <td class="${parseFloat(grid.returnRate) >= 0 ? 'profit' : 'loss'}">
                    ${grid.returnRate}%
                </td>
            </tr>
        `).join('');
    }

    /**
     * 更新总投入金额显示
     */
    updateTotalAmountDisplay(gridData) {
        // 计算各网格类型的投入金额
        const smallAmount = gridData.filter(grid => grid.gridType === '小网')
            .reduce((sum, grid) => sum + parseFloat(grid.buyAmount), 0);
        const mediumAmount = gridData.filter(grid => grid.gridType === '中网')
            .reduce((sum, grid) => sum + parseFloat(grid.buyAmount), 0);
        const largeAmount = gridData.filter(grid => grid.gridType === '大网')
            .reduce((sum, grid) => sum + parseFloat(grid.buyAmount), 0);
        
        const totalAmount = smallAmount + mediumAmount + largeAmount;

        // 更新显示
        document.getElementById('totalAmountValue').textContent = `¥${totalAmount.toFixed(2)}`;
        document.getElementById('smallAmountValue').textContent = `¥${smallAmount.toFixed(2)}`;
        document.getElementById('mediumAmountValue').textContent = `¥${mediumAmount.toFixed(2)}`;
        document.getElementById('largeAmountValue').textContent = `¥${largeAmount.toFixed(2)}`;

        // 显示总投入金额区域
        document.getElementById('totalAmountDisplay').style.display = 'block';
    }

    /**
     * 更新剩余股数统计显示
     */
    updateRemainingSharesDisplay(gridData) {
        // 计算各网格类型的剩余股数
        const smallRemaining = gridData.filter(grid => grid.gridType === '小网')
            .reduce((sum, grid) => sum + grid.remainingShares, 0);
        const mediumRemaining = gridData.filter(grid => grid.gridType === '中网')
            .reduce((sum, grid) => sum + grid.remainingShares, 0);
        const largeRemaining = gridData.filter(grid => grid.gridType === '大网')
            .reduce((sum, grid) => sum + grid.remainingShares, 0);
        
        const totalRemaining = smallRemaining + mediumRemaining + largeRemaining;

        // 更新显示
        document.getElementById('totalRemainingShares').textContent = `${totalRemaining}股`;
        document.getElementById('smallRemainingShares').textContent = `${smallRemaining}股`;
        document.getElementById('mediumRemainingShares').textContent = `${mediumRemaining}股`;
        document.getElementById('largeRemainingShares').textContent = `${largeRemaining}股`;

        // 显示剩余股数统计区域
        document.getElementById('remainingSharesDisplay').style.display = 'block';
    }


    /**
     * 显示结果摘要
     */
    showResultSummary(params, stats) {
        const enabledStrategies = [];
        if (params.enableProfitRetention) enabledStrategies.push('利润留存');
        if (params.enableProgressiveBetting) enabledStrategies.push('逐格加码');
        if (params.enableMultiGrid) enabledStrategies.push('大中小网');

        const summary = `
综合策略测试完成！

ETF品种: ${params.etfName}
初始价格: ${params.initialPrice}
网格模式: ${params.gridMode === 'percentage' ? '百分比模式' : '固定步长模式'}
启用策略: ${enabledStrategies.join(' + ')}

测试结果:
- 总收益: ¥${stats.totalProfit}
- 总收益率: ${stats.totalReturnRate}%
- 完成交易: ${stats.completedTrades}笔
- 最大回撤: ¥${stats.maxDrawdown}
- 保留利润: ¥${stats.retainedProfits}
        `;

        alert(summary);
    }
}

// 全局实例
const gridSystem3 = new GridTradingSystem3();

// 运行综合策略测试
function runComprehensiveTest() {
    // 检查所有必需的元素是否存在
    const requiredElements = [
        'etfName', 'initialPrice', 'gridMode', 'gridSize', 'gridStep', 'baseAmount', 'maxDecline',
        'enableProfitRetention', 'enableProgressiveBetting', 'progressiveMode', 'increaseRate', 
        'increaseAmount', 'startFromGrid', 'smallGridLayers', 'mediumGridLayers', 'largeGridLayers',
        'smallGridSize', 'mediumGridSize', 'largeGridSize', 'smallGridStep', 'mediumGridStep', 
        'largeGridStep', 'smallGridProgressive', 'mediumGridProgressive', 'largeGridProgressive'
    ];
    
    for (const elementId of requiredElements) {
        const element = document.getElementById(elementId);
        if (!element) {
            console.error(`Element with id '${elementId}' not found`);
            alert(`错误：找不到元素 ${elementId}`);
            return;
        }
    }

    const params = {
        etfName: document.getElementById('etfName').value,
        initialPrice: parseFloat(document.getElementById('initialPrice').value),
        gridMode: document.getElementById('gridMode').value,
        gridSize: parseFloat(document.getElementById('gridSize').value),
        gridStep: parseFloat(document.getElementById('gridStep').value),
        baseAmount: parseFloat(document.getElementById('baseAmount').value),
        maxDecline: parseFloat(document.getElementById('maxDecline').value),
        
        // 策略开关
        enableProfitRetention: document.getElementById('enableProfitRetention').checked,
        
        enableProgressiveBetting: document.getElementById('enableProgressiveBetting').checked,
        progressiveMode: document.getElementById('progressiveMode').value,
        increaseRate: parseFloat(document.getElementById('increaseRate').value),
        increaseAmount: parseFloat(document.getElementById('increaseAmount').value),
        startFromGrid: parseInt(document.getElementById('startFromGrid').value),
        
        smallGridLayers: parseInt(document.getElementById('smallGridLayers').value),
        mediumGridLayers: parseInt(document.getElementById('mediumGridLayers').value),
        largeGridLayers: parseInt(document.getElementById('largeGridLayers').value),
        smallGridSize: parseFloat(document.getElementById('smallGridSize').value),
        mediumGridSize: parseFloat(document.getElementById('mediumGridSize').value),
        largeGridSize: parseFloat(document.getElementById('largeGridSize').value),
        smallGridStep: parseFloat(document.getElementById('smallGridStep').value),
        mediumGridStep: parseFloat(document.getElementById('mediumGridStep').value),
        largeGridStep: parseFloat(document.getElementById('largeGridStep').value),
        smallGridProgressive: document.getElementById('smallGridProgressive').checked,
        mediumGridProgressive: document.getElementById('mediumGridProgressive').checked,
        largeGridProgressive: document.getElementById('largeGridProgressive').checked
    };

    // 生成综合网格数据
    const gridData = gridSystem3.generateComprehensiveGrid(params);
    gridSystem3.updateGridTable(gridData);
    gridSystem3.updateTotalAmountDisplay(gridData);
    gridSystem3.updateRemainingSharesDisplay(gridData);

    // 运行模拟
    const simulationResult = gridSystem3.simulateComprehensiveTrading(params, gridData);
    const stats = gridSystem3.calculateComprehensiveStatistics(gridData, simulationResult, params);
    
    gridSystem3.updateStatsGrid(stats);
    gridSystem3.showResultSummary(params, stats);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('ETF网格交易3.0综合策略系统已加载');
});